import { BadRequestException, Module } from '@nestjs/common';
import { FileService } from './file.service';
import { FileController } from './file.controller';
import { MulterModule } from '@nestjs/platform-express';

import { diskStorage } from 'multer';
import { existsSync, mkdirSync } from 'fs';
import { extname, join } from 'path';

const image = ['gif', 'png', 'jpg', 'jpeg', 'bmp', 'webp'];
const video = ['mp4', 'webm'];
const audio = ['mp3', 'wav', 'ogg'];

@Module({
  imports: [
    MulterModule.register({
      storage: diskStorage({
        // 配置上传后文件存储位置
        destination: (req, file, cb) => {
          console.log(req.path);

          // 根据上传的文件类型将图片视频音频和其他类型文件分别存到对应英文文件夹
          const mimeType = file.mimetype.split('/')[1];
          let temp = 'other';
          image.filter((item) => item === mimeType).length > 0
            ? (temp = 'image')
            : '';
          video.filter((item) => item === mimeType).length > 0
            ? (temp = 'video')
            : '';
          audio.filter((item) => item === mimeType).length > 0
            ? (temp = 'audio')
            : '';

          // const filePath = `${config.fileTempPath}${temp}`;
          // const filePath = join(__dirname, temp);
          // C:\Users\陶奇林\Desktop\tql-nest\dist\src\file\image
          let filePath = null;
          const urlAarry = req.path.split('/');
          if (urlAarry[urlAarry.length - 1] === 'uploadPostCoverUrl') {
            filePath = join('public', 'uploadPostCover', temp);
          } else {
            filePath = join('public', temp);
          }
          // 判断文件夹是否存在，不存在则自动生成
          if (!existsSync(filePath)) {
            mkdirSync(filePath);
          }
          return cb(null, `${filePath}`);
        },
        // 配置文件名称
        filename: async (req, file, cb) => {
          const fileName = `${
            new Date().getTime() + extname(file.originalname)
          }`;
          return cb(null, fileName);
        },
      }),
      fileFilter(req, file, cb) {
        const mimeType = file.mimetype.split('/')[1].toLowerCase();
        let temp = 'other';
        image.filter((item) => item === mimeType).length > 0
          ? (temp = 'image')
          : '';
        video.filter((item) => item === mimeType).length > 0
          ? (temp = 'video')
          : '';
        audio.filter((item) => item === mimeType).length > 0
          ? (temp = 'audio')
          : '';
        if (temp === 'other') {
          return cb(new BadRequestException('文件格式错误！'), false);
        }
        return cb(null, true);
      },
    }),
  ],
  controllers: [FileController],
  providers: [FileService],
})
export class FileModule {}
